package core;

import com.sun.imageio.plugins.gif.GIFImageMetadata;
import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
import fileoperation.FileDeletion;
import gitobject.*;
import repository.Repository;
import zlib.ZLibUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Map;

public class JitReset {

    public static void soft(String commitId) throws Exception {
        Head head = new Head(commitId);
    }

    public static void hard(String commitId) throws Exception {

        Commit commit = Commit.deserialize(commitId);
        if (commit != null) {
            File workTree = new File(Repository.getWorkTree());
            File[] fileList = workTree.listFiles();
            for (File file : fileList) {
                if (!file.getAbsolutePath().equals(Repository.getWorkTree() + File.separator + ".jit")) {
                        FileDeletion.deleteFile(file);
                }
            }
            Iterator<Map.Entry<String, GitObject>> iterator = commit.getCommitterTree().entrySet().iterator();
            while(iterator.hasNext()){
                Map.Entry<String, GitObject> entry = iterator.next();
                rewrite(entry.getValue());      	// 将Commit对象里Hashmap的blob或者Tree对象重新写入工作区
            }

        }
    }

    public static void rewrite(GitObject gitObject) throws Exception {
         if(gitObject.getFmt().equals("Blob")){
            File file = gitObject.getFile();
            if(!file.exists()){
                String parentPath = file.getAbsolutePath().substring(0, file.getAbsolutePath().lastIndexOf(File.separator));
                new File(parentPath).mkdirs();
                byte[] data = ZLibUtils.decompress(Base64.decode(gitObject.getValue()));
                GitObject.writeFile(file, data);
            }
         }

        if (gitObject.getFmt().equals("tree")) {
            ArrayList<GitObject> trl = ((Tree) gitObject).getTreeList();
            Iterator<GitObject> itr = trl.iterator();
            while (itr.hasNext())
                rewrite(itr.next());
        }
    }

    public static void mixed(String commitId) throws Exception {
        Commit commit = Commit.deserialize(commitId);
        File indexFile = new File(Repository.getGitDir() + File.separator + "index");

        if(commit != null && !indexFile.exists()){
            Iterator<Map.Entry<String, GitObject>> iterator = commit.getCommitterTree().entrySet().iterator();
            GitObject gitObject = iterator.next().getValue();
            JitAdd.add(gitObject.getFile());
            Index index = Index.deserialize(indexFile);
            index.fileOb = commit.getCommitterTree();
        }
        else {
            System.out.println("没有可reset的对象");
            System.exit(0);
        }
    }

}
